<template>
  <AppPage :show-footer="true">
    <div class="flex">
      <n-card class="w-30%">
        <div class="flex items-center">
          <n-avatar round :size="60" :src="userStore.avatar" />
          <div class="ml-20 flex-col">
            <span class="text-20 opacity-80">Hello, {{ userStore.name }}</span>
            <span class="mt-4 opacity-50">今日事，今日毕。</span>
          </div>
        </div>

        <p class="mt-20 text-14 opacity-60">一个人几乎可以在任何他怀有无限热忱的事情上成功。</p>
        <p class="mt-12 text-right text-12 opacity-40">—— 查尔斯·史考伯</p>
      </n-card>
      <n-card class="ml-12 w-70%">
        <h3 class="text-20 font-normal opacity-90">⚡️欢迎使用 Vue Naive Admin</h3>
        <p class="mt-8 opacity-60">
          后台信息：{{ message }}
        </p>
        <footer class="mt-24 flex items-center justify-end">
          <n-button tag="a" href="https://zclzone.github.io/vue-naive-admin-docs" target="_blank" type="primary" ghost>
            开发文档
          </n-button>
          <n-button tag="a" href="https://github.com/zclzone/vue-naive-admin" target="_blank" type="primary"
            class="ml-12">
            代码仓库
          </n-button>
        </footer>
      </n-card>
    </div>
    <div class="mt-12 flex">
      <n-card title="项目" segmented>
        <template #header-extra>
          <n-button text type="primary" @click="refresh">刷新</n-button>
        </template>
        <div>
          <el-table height="320" :data="dictionary" class="w-full" row-key="id" lazy border :load="loadChildren"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
            <el-table-column prop="id" label="ID" />
            <el-table-column prop="parentId" label="父级ID" />
            <el-table-column prop="name" label="名字" />
          </el-table>
        </div>
      </n-card>

      <n-card class="ml-12" title="技术栈" segmented>
        <VChart :option="skillsOption" class="wh-full" autoresize />
      </n-card>
    </div>

    <n-card class="mt-12" title="用户" segmented>
      <div>
        <h3>搜索用户</h3>
        <el-divider></el-divider>
        <el-form :model="searchUser" :rules="rules1" label-width="100px" status-icon size="default">
          <el-form-item label="ID：">
            <el-input v-model="searchUser.id" />
          </el-form-item>
          <el-form-item label="用户名：">
            <el-input v-model="searchUser.name" />
          </el-form-item>
          <el-form-item label="最小余额：">
            <el-input type="number" v-model="searchUser.minMoney" />
          </el-form-item>
          <el-form-item label="最大余额：">
            <el-input type="number" v-model="searchUser.maxMoney" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">搜索</el-button>
            <el-button type="warning" @click="searchUser = {}">重置</el-button>
          </el-form-item>
        </el-form>

        <el-divider></el-divider>
        <h3>用户数据</h3>
        <el-table :data="pageData.users" height="320" stripe>
          <el-table-column prop="id" label="ID" sortable width="100" />
          <el-table-column prop="username" label="用户" />
          <el-table-column prop="password" label="密码" />
          <el-table-column prop="money" sortable label="余额" />
          <el-table-column prop="sex" label="性别" width="80" />
          <el-table-column fixed="right" label="操作" width="180">
            <template #default="item">
              <el-button type="primary" size="small" @click="showUser(item.row)">查看</el-button>
              <el-button type="danger" size="small" @click="deleteUser(item.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog v-model="dialogVisible" :title="`用户信息-【${user.id}】`" width="80%" :before-close="handleClose">
          <div>
            <el-form :model="user" :rules="rules2" label-width="80px" size="small">
              <el-form-item label="用户名：" prop="username">
                <el-input v-model="user.username" />
              </el-form-item>
              <el-form-item label="密码：" prop="password">
                <el-input type="password" v-model="user.password" />
              </el-form-item>
              <el-form-item label="余额：" prop="money">
                <el-input type="number" v-model="user.money" />
              </el-form-item>
            </el-form>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="cancelUpdate">取消</el-button>
              <el-button type="warning" @click="confirmUpdate">确定修改</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </n-card>
  </AppPage>
</template>

<script setup>
import { useUserStore } from '@/store'
import * as echarts from 'echarts/core'
import { TooltipComponent, GridComponent, LegendComponent } from 'echarts/components'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from 'vue-echarts'
import _ from 'lodash-es'
import { ElMessage } from 'element-plus'

import { request } from '@/utils'

const userStore = useUserStore()

const rules1 = {}
const rules2 = {
  username: [
    { min: 3, max: 16, message: '长度3-16', trigger: 'change' },
    { required: true, message: '用户名必须填写', trigger: 'blur' },
  ],
}
const dialogVisible = ref(false)
const user = ref({
  id: null,
  password: null,
  money: null,
})
const pageData = ref({
  current: 0,
  pages: 0,
  users: [],
})
const searchUser = ref({
  id: null,
  name: null,
  minMoney: 10000,
  maxMoney: 1000000,
})
const dictionary = ref([])

const cancelUpdate = () => {
  dialogVisible.value = false
}
const handleClose = () => {
  dialogVisible.value = false
}
const confirmUpdate = () => {
  request.put('/api/user', user.value)
    .then(response => {
      console.log('修改成功：', response)
      dialogVisible.value = false
      ElMessage.success('修改成功！')
    })
    .catch(e => console.log('请求出错：', e))
}
const showUser = u => {
  user.value = u
  dialogVisible.value = true
}
const addUser = u => {
  console.log('未实现……')
}
const deleteUser = user => {
  request.delete(`/api/user/${user.id}`)
    .then(response => {
      _.remove(pageData.value.users, item => item.id === user.id)
      ElMessage.success('删除成功')
    })
    .catch(e => console.log('请求出错：', e))
}
const search = () => {
  request.post('/api/user/search', searchUser.value, { params: { page: 1, size: 10, } })
    .then(response => {
      const { current, pages, records } = response.data
      const users = records.map(user => {
        user.password = '******'
        return user
      })
      pageData.value = { current, pages, users, }
    })
    .catch(e => console.log('请求出错：', e))
}

const loadChildren = (dict, _, resolve) => {
  request
    .get(`/api/address/parent/${dict.id}`)
    .then((data) =>
      resolve(
        data.data.map((child) => {
          child.hasChildren = true
          child.parentId = dict.id
          return child
        })
      )
    )
    .catch(() => resolve([]))
}
const refresh = () => {
  request
    .get(`/api/address/deep/0`)
    .then((data) => {
      dictionary.value = data.data.map((child) => {
        child.hasChildren = true
        child.parentId = 0
        return child
      })
    })
    .catch((e) => console.error(e))
}

const info = () => {
  request.get('/api/info')
    .then(data => {
      if (data.code === 0 || data.code === 200) {
        message.value = data.data
      }
    })
    .catch(e => console.log('error:', e))
}

const message = ref("空空如也")
onMounted(() => {
  info()
  refresh()
  search()
})

echarts.use([
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
  PieChart,
])

const trendOption = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999',
      },
    },
  },
  legend: {
    top: '5%',
    data: ['star', 'fork'],
  },
  xAxis: [
    {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      axisPointer: {
        type: 'shadow',
      },
    },
  ],
  yAxis: [
    {
      type: 'value',
      min: 0,
      max: 3000,
      interval: 500,
      axisLabel: {
        formatter: '{value}',
      },
    },
    {
      type: 'value',
      min: 0,
      max: 500,
      interval: 100,
      axisLabel: {
        formatter: '{value}',
      },
    },
  ],
  series: [
    {
      name: 'star',
      type: 'line',
      data: [200, 320, 520, 550, 600, 805, 888, 950, 1300, 2503, 2702, 2712],
    },
    {
      name: 'fork',
      yAxisIndex: 1,
      type: 'bar',
      data: [40, 72, 110, 115, 121, 175, 180, 201, 260, 398, 423, 455],
    },
  ],
}

const skillsOption = {
  tooltip: {
    trigger: 'item',
    formatter({ name, value }) {
      return `${name} ${value}%`
    },
  },
  legend: {
    left: 'center',
  },
  series: [
    {
      top: '7%',
      type: 'pie',
      radius: ['40%', '85%'],
      avoidLabelOverlap: true,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2,
      },
      label: {
        show: false,
        position: 'center',
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 36,
          fontWeight: 'bold',
        },
      },
      labelLine: {
        show: false,
      },
      data: [
        { value: 38.5, name: 'Vue' },
        { value: 37.0, name: 'JavaScript' },
        { value: 6.5, name: 'CSS' },
        { value: 6.2, name: 'HTML' },
        { value: 1.8, name: 'Other' },
      ],
    },
  ],
}
</script>
